import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:go_router/go_router.dart';
import 'package:hinge/common/index.dart';
import 'package:hinge/store/root_store.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'dart:io';

class SetupPage extends StatefulWidget {
  const SetupPage({super.key});

  @override
  State<SetupPage> createState() => _SetupPageState();
}

class _SetupPageState extends State<SetupPage> {
  final _rootStore = RootStore();
  final TextEditingController _nicknameController = TextEditingController();
  final TextEditingController _descriptionController = TextEditingController();

  @override
  void initState() {
    super.initState();
    _initData();
  }

  @override
  void dispose() {
    _nicknameController.dispose();
    _descriptionController.dispose();
    super.dispose();
  }

  Future<void> _initData() async {
    await _rootStore.setupStore.init();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(AssetsImages.splash),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          child: Observer(
            builder: (_) {
              final isGuest = _rootStore.setupStore.isGuest;
              final user = _rootStore.setupStore.currentUser;

              return Column(
                children: [
                  _buildHeader(context),
                  SizedBox(height: 12.h),
                  _buildUserInfo(context, user, isGuest),
                  SizedBox(height: 30.h),
                  _buildSettingItems(context),
                  Spacer(),
                  _buildButtons(context),
                  SizedBox(height: 175.h),
                ],
              );
            },
          ),
        ),
      ),
    );
  }

  Widget _buildHeader(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 15.h),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          GestureDetector(
            onTap: () => GoRouter.of(context).pop(),
            child: Icon(IconFont.back, color: Colors.white, size: 28.sp),
          ),
          SizedBox(width: 10.w),
          Text(
            'Set Up',
            style: TextStyle(
              fontSize: 20.sp,
              fontWeight: FontWeight.w700,
              color: Colors.white,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildUserInfo(BuildContext context, UserModel? user, bool isGuest) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.end,
      children: [
        SizedBox(width: 76.w),
        GestureDetector(
          onTap: () {
            _rootStore.setupStore.pickAvatar(context);
          },
          child: Stack(
            children: [
              CircleAvatar(
                radius: 30.r,
                backgroundImage:
                    user?.avatar != null && user!.avatar.startsWith('/')
                        ? FileImage(File(user.avatar))
                        : AssetImage(user?.avatar ?? AssetsImages.avatar1)
                            as ImageProvider,
              ),
              Positioned.fill(
                child: Container(
                  decoration: BoxDecoration(
                    color: Colors.black.withOpacity(0.2),
                    shape: BoxShape.circle,
                  ),
                  child: Center(
                    child: Icon(
                      IconFont.photo,
                      color: Colors.white,
                      size: 20.sp,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
        SizedBox(width: 15.w),
        Expanded(
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text(
                user?.nickname ?? "Hack",
                style: TextStyle(
                  fontSize: 20.sp,
                  fontWeight: FontWeight.w400,
                  color: Colors.white,
                ),
              ),
              SizedBox(width: 8.w),
              GestureDetector(
                onTap: () {
                  _showNicknameEditDialog(context, user);
                },
                child: Icon(IconFont.edit2, color: Colors.white, size: 20.sp),
              ),
            ],
          ),
        ),
      ],
    );
  }

  // 显示修改用户名对话框
  void _showNicknameEditDialog(BuildContext context, UserModel? user) {
    _nicknameController.text = user?.nickname ?? '';

    // 先显示一个自定义对话框
    showDialog(
      context: context,
      barrierDismissible: false, // 禁止点击外部关闭对话框
      builder:
          (context) => PopScope(
            canPop: true,
            onPopInvokedWithResult: (didPop, result) {
              // 确保在返回键关闭对话框时不进行额外操作
              // _nicknameController会在组件dispose时释放
            },
            child: Dialog(
              backgroundColor: Colors.transparent,
              elevation: 0,
              child: Container(
                width: 325.w,
                padding: EdgeInsets.all(24.w),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(20.r),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.1),
                      blurRadius: 10,
                      offset: const Offset(0, 4),
                    ),
                  ],
                ),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(
                      'Edit Username',
                      style: TextStyle(
                        fontSize: 20.sp,
                        fontWeight: FontWeight.w600,
                        color: const Color(0xFF2D1457),
                      ),
                    ),
                    SizedBox(height: 20.h),
                    TextField(
                      controller: _nicknameController,
                      decoration: InputDecoration(
                        hintText: 'Enter new username',
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(12.r),
                          borderSide: BorderSide(color: Colors.grey.shade300),
                        ),
                        enabledBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(12.r),
                          borderSide: BorderSide(color: Colors.grey.shade300),
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(12.r),
                          borderSide: BorderSide(
                            color: const Color(0xFFA794FD),
                          ),
                        ),
                        contentPadding: EdgeInsets.symmetric(
                          horizontal: 16.w,
                          vertical: 12.h,
                        ),
                      ),
                      maxLength: 20,
                    ),
                    SizedBox(height: 24.h),
                    Row(
                      children: [
                        Expanded(
                          child: _buildButton(
                            text: 'Cancel',
                            onPressed: () => Navigator.of(context).pop(),
                            color: Colors.grey.shade200,
                            textColor: Colors.black87,
                          ),
                        ),
                        SizedBox(width: 16.w),
                        Expanded(
                          child: _buildButton(
                            text: 'Update',
                            onPressed: () {
                              final newNickname =
                                  _nicknameController.text.trim();
                              if (newNickname.isNotEmpty) {
                                _rootStore.setupStore.updateUserNickname(
                                  newNickname,
                                );
                                Navigator.of(context).pop();

                                // 显示更新成功提示
                                EasyLoading.showSuccess(
                                  'Username updated successfully',
                                );
                              }
                            },
                            color: const Color(0xFFA794FD),
                            textColor: Colors.white,
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ),
    );
  }

  // 构建按钮
  Widget _buildButton({
    required String text,
    required VoidCallback onPressed,
    required Color color,
    required Color textColor,
  }) {
    return ElevatedButton(
      onPressed: onPressed,
      style: ElevatedButton.styleFrom(
        backgroundColor: color,
        foregroundColor: textColor,
        padding: EdgeInsets.symmetric(vertical: 14.h),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(30.r),
        ),
        elevation: 0,
      ),
      child: Text(
        text,
        style: TextStyle(fontSize: 16.sp, fontWeight: FontWeight.w600),
      ),
    );
  }

  Widget _buildSettingItems(BuildContext context) {
    final items = [
      {'title': 'Modify signature', 'icon': Icons.arrow_forward_ios},
      {'title': 'Privacy Policy', 'icon': Icons.arrow_forward_ios},
      {'title': 'Terms Of service', 'icon': Icons.arrow_forward_ios},
      {'title': 'Eula', 'icon': Icons.arrow_forward_ios},
    ];

    return Column(
      children:
          items.map((item) {
            return _buildSettingItem(
              context,
              title: item['title'] as String,
              icon: item['icon'] as IconData,
            );
          }).toList(),
    );
  }

  Widget _buildSettingItem(
    BuildContext context, {
    required String title,
    required IconData icon,
  }) {
    return GestureDetector(
      onTap: () {
        _rootStore.setupStore.handleSettingItemClick(context, title);
      },
      child: Container(
        margin: EdgeInsets.symmetric(horizontal: 20.w, vertical: 6.h),
        padding: EdgeInsets.symmetric(horizontal: 15.w, vertical: 12.h),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              title,
              style: TextStyle(
                fontSize: 14.sp,
                fontWeight: FontWeight.w400,
                color: Colors.white,
                fontFamily: 'Inter',
              ),
            ),
            Icon(icon, color: Colors.white, size: 20.sp),
          ],
        ),
      ),
    );
  }

  Widget _buildButtons(BuildContext context) {
    return Column(
      children: [
        Container(
          width: double.infinity,
          height: 50.h,
          margin: EdgeInsets.symmetric(horizontal: 20.w),
          child: ElevatedButton(
            onPressed: () {
              _rootStore.setupStore.showLogoutConfirmDialog(context);
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: Color(0xFFBD88FF),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(26.r),
              ),
            ),
            child: Text(
              'Log Out',
              style: TextStyle(
                fontSize: 18.sp,
                fontWeight: FontWeight.w600,
                color: Colors.white,
              ),
            ),
          ),
        ),
        SizedBox(height: 15.h),
        Container(
          width: double.infinity,
          height: 50.h,
          margin: EdgeInsets.symmetric(horizontal: 20.w),
          child: OutlinedButton(
            onPressed: () {
              _rootStore.setupStore.showDeleteAccountConfirmDialog(context);
            },
            style: OutlinedButton.styleFrom(
              side: BorderSide(color: Color(0xFFBD88FF)),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(25.r),
              ),
            ),
            child: Text(
              'Delete account',
              style: TextStyle(
                fontSize: 17.sp,
                fontWeight: FontWeight.w700,
                color: Color(0xFFBD88FF),
              ),
            ),
          ),
        ),
      ],
    );
  }
}
